package com.ms.seguridad.support;

import com.ms.jsf.JsfBeanBase;
import com.ms.seguridad.UserInfo;
import com.ms.seguridad.service.SecurityService;
import org.primefaces.model.menu.MenuModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Enumeration;

/**
 * User: gmc
 * Date: 30/04/13
 */
@Scope("session")
@Component
public class ViewInfoMgr implements Serializable {
    private static final Logger LOG = LoggerFactory.getLogger(ViewInfoMgr.class);
    private UserInfo userInfo;
    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    SecurityService securityService;

    String page;
    Object currentJsfBean;

    private MenuModel toolBarMenu;
    private String iconMessage;
    // Message that will be set in the message window
    protected String messageStr;
    private String fullMessageStr;

    @PostConstruct
    public void inicializarViewInfo() {
//        userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        FacesContext facesContext = FacesContext.getCurrentInstance();
//        setToolBarMenu(WebHelper.getToolBarMenu(facesContext, userInfo.getModulesType()));
    }



    public void cleanSession() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        Enumeration e = session.getAttributeNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            Object object = session.getAttribute(key);
            if (object != null && object instanceof JsfBeanBase) {
                session.removeAttribute(key);
            }
        }
    }

    private void cleanFromSession(String key) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        session.removeAttribute(key);
    }

    protected void setPage(String page) {
        LOG.debug("Setting page:{}", page);
        this.page = page;
        String beanName = getJsfBeanNameFrom(page);
        LOG.debug("Bean name:{}", beanName);
        if (applicationContext.containsBean(beanName)) {
            Object bean = applicationContext.getBean(beanName);
            currentJsfBean = bean;
            LOG.debug("Changing jsf bean to:{} new Page:{}", bean, page);
        } else {
            LOG.debug("Jsf bean was not changed remain in:{} new page: {} posible bean discarded:{}", new Object[]{currentJsfBean, page, beanName});
        }
    }

    private String getJsfBeanNameFrom(String page) {
        int idx = page.lastIndexOf("/");
        int idDotx = page.lastIndexOf(".");
        return page.substring(idx + 1, idDotx) + "JsfBean";
    }

    public Object getCurrentJsfBean() {
        if (currentJsfBean == null) {
            currentJsfBean = this;
        }
        return currentJsfBean;
    }

    public String getPage() {
        return page;
    }

    public void setCurrentJsfBean(Object currentJsfBean) {
        this.currentJsfBean = currentJsfBean;
    }

    public void goToPage(String page) {
        setPage(page);
    }

    public String getIconMessage() {
        return iconMessage;
    }

    public void setIconMessage(String iconMessage) {
        this.iconMessage = iconMessage;
    }

    public String getMessageStr() {
        return messageStr;
    }

    public void setMessageStr(String messageStr) {
        this.messageStr = messageStr;
    }

    public void setMessageInfo(String iconMessage, String errorMessage) {
        setMessageInfo(iconMessage, errorMessage, "");
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void setMessageInfo(String iconMessage, String errorMessage, String fullMsg) {
        this.iconMessage = iconMessage;
        this.messageStr = errorMessage;
        this.fullMessageStr = fullMsg;
    }

    public String getFullMessageStr() {
        return fullMessageStr;
    }

    public void close(String simpleName) {
        String beanName = getBeanName(simpleName);
        cleanFromSession(beanName);
    }

    private String getBeanName(String shortClassName) {
        if (!shortClassName.startsWith("FN")) {
            return StringUtils.uncapitalize(shortClassName);
        }
        return "fn" + shortClassName.substring(2);
    }

    public MenuModel getToolBarMenu() {
        return toolBarMenu;
    }

    public void setToolBarMenu(MenuModel toolBarMenu) {
        this.toolBarMenu = toolBarMenu;
    }
}
